package com.adong.tv.ui.viewmodel;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.adong.tv.data.ApiConfig;
import com.adong.tv.data.ApiResult;
import com.adong.tv.data.MovieRepository;
import com.adong.tv.model.ApiSource;
import com.adong.tv.model.Category;
import com.adong.tv.model.Movie;

import java.util.List;

/**
 * 主界面ViewModel
 */
public class MainViewModel extends ViewModel {
    
    private final MovieRepository repository;
    private final MutableLiveData<Integer> selectedCategoryId = new MutableLiveData<>();
    private final MutableLiveData<String> searchKeyword = new MutableLiveData<>();
    private final MutableLiveData<ApiSource> currentApi = new MutableLiveData<>();
    
    public MainViewModel() {
        repository = MovieRepository.getInstance();
        currentApi.setValue(ApiConfig.getCurrentApi());
    }
    
    /**
     * 获取分类列表
     * @return 分类列表LiveData
     */
    public LiveData<ApiResult<List<Category>>> getCategories() {
        return repository.getCategories();
    }
    
    /**
     * 获取电影列表
     * @param page 页码
     * @return 电影列表LiveData
     */
    public LiveData<ApiResult<List<Movie>>> getMovieList(int page) {
        return repository.getMovieList(page, selectedCategoryId.getValue(), searchKeyword.getValue());
    }

    public LiveData<ApiResult<List<Movie>>> getSearchList(int page) {
        return repository.getSearchList(page, searchKeyword.getValue());
    }
    
    /**
     * 设置当前选中的分类ID
     * @param categoryId 分类ID
     */
    public void setSelectedCategory(Integer categoryId) {
        selectedCategoryId.setValue(categoryId);
    }
    
    /**
     * 获取当前选中的分类ID
     * @return 分类ID LiveData
     */
    public LiveData<Integer> getSelectedCategory() {
        return selectedCategoryId;
    }
    
    /**
     * 设置搜索关键字
     * @param keyword 关键字
     */
    public void setSearchKeyword(String keyword) {
        searchKeyword.setValue(keyword);
    }
    
    /**
     * 获取搜索关键字
     * @return 关键字LiveData
     */
    public LiveData<String> getSearchKeyword() {
        return searchKeyword;
    }
    
    /**
     * 切换API源
     * @param apiSource API源
     */
    public void switchApiSource(ApiSource apiSource) {
        ApiConfig.setCurrentApi(apiSource);
        currentApi.setValue(apiSource);
        repository.refreshApiService();
    }
    
    /**
     * 获取当前API源
     * @return API源LiveData
     */
    public LiveData<ApiSource> getCurrentApi() {
        return currentApi;
    }
    
    /**
     * 获取所有API源
     * @return API源列表
     */
    public List<ApiSource> getAllApiSources() {
        return ApiConfig.getApiSources();
    }


}